﻿CREATE PROCEDURE [acms].[UserPostUpload_Put]
	@Id int,
	@UserId int,
	@PostId int,
	@FileId int,
	@Title varchar(500),
	@Comment varchar(2000),
	@IPAddress varchar(16),
	@Reviewed bit,
	@Reported bit,
	@Suspended int,
	@Created datetime,
	@TextFields XML,
	@ConcurencyId rowversion,
	@IdOut int output,
	@UserNameOut varchar(50) output,
	@AverageVoteOut decimal(5,4) output,
	@ConcurencyIdOut rowversion output

AS
	if(@Id is null or @Id = 0)
	begin
		insert into UserPostUpload
			(UserId, PostId, FileId, Title, Comment, IPAddress, Reviewed, Reported, Suspended, Created, TextFields)
		values
			(@UserId, @PostId, @FileId, @Title, @Comment, @IPAddress, @Reviewed, @Reported, @Suspended, @Created, @TextFields)
		set @IdOut = @@identity
	end
	else if exists(select null from [UserPostUpload_View] with (nolock) where Id = @Id and ConcurencyId = @ConcurencyId)
	begin
		update UserPostUpload
		set
			UserId = @UserId,
			PostId = @PostId,
			FileId = @FileId,
			Title = @Title,
			Comment = @Comment,
			IPAddress = @IPAddress,
			Reviewed = @Reviewed,
			Reported = @Reported,
			Suspended = @Suspended,
			TextFields = @TextFields
		where Id = @Id
			and ConcurencyId = @ConcurencyId
		set @IdOut = @Id
	end
	else if exists(select null from [UserPostUpload_View] with (nolock) where Id = @Id)
		return -100
	else
		return -200


	select 
		@UserNameOut = UserName, 
		@AverageVoteOut = AverageVote, 
		@ConcurencyIdOut = ConcurencyId
	from UserPostUpload_View with (nolock)
	where Id = @IdOut
RETURN 0;